package com.joysuch.wwyt.bp.repository;

import com.joysuch.wwyt.bp.entity.investigate.BpInvestigateTask;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.Date;
import java.util.List;

/**
 * @Author ZhangDong
 * @Date 2020/12/8 10:21
 */
public interface BpInvestigateTaskDao extends JpaRepository<BpInvestigateTask, Long>, JpaSpecificationExecutor<BpInvestigateTask> {

    List<BpInvestigateTask> findByUserIdAndCheckDateAndStatus(Long userId, Date checkDate, String status);

    List<BpInvestigateTask> findByPlanIdAndCheckDate(Long planId, Date checkDate);

    @Query(value = "select * from wwyt_bp_investigate_task where plan_id = ?1 and check_date >= ?2 and check_date <= ?3",nativeQuery = true)
    List<BpInvestigateTask> findByPlanIdAndCheckDate(Long planId, Date startDate, Date endDate);

    List<BpInvestigateTask> findByCheckDateLessThanAndStatusAndSourceType(Date checkDate, String status,Integer sourceType);

    List<BpInvestigateTask> findByDeadlineLessThanAndStatusAndSourceType(Date deadline, String status,Integer sourceType);

    List<BpInvestigateTask> findByPlanId(Long planId);

    @Query("select planId from BpInvestigateTask where id in (?1)")
    List<Long> findPlanIdByIdIn(List<Long> planId);

    @Query("update BpInvestigateTask t set t.deleteFlag = '1' where t.id in (:taskIdList)")
    @Modifying
    void deleteTasks(List<Long> taskIdList);

    @Query(value = "select * " +
            "from wwyt_bp_investigate_task " +
            "where status = '未完成' " +
            "  and ((period_unit in ('年', '月') and deadline < ?1) " +
            "    or (period_unit = '日' and deadline < ?2) " +
            "    or (period_unit = '时' and deadline < ?3))",nativeQuery = true)
    List<BpInvestigateTask> findComingTimeOut(Date yearAdvance,Date dayAdvance,Date hourAdvance);

    @Query(value = "select assign_user from wwyt_bp_investigate_task_assign where task_id = ?1",nativeQuery = true)
    List<Long> getAssignUserIdsByTaskId(Long taskId);

    @Query(value = "select task.* " +
            "from wwyt_bp_investigate_task task " +
            "         inner join wwyt_bp_investigate_plan plan " +
            "                    on task.plan_id = plan.id and task.status = '未完成' " +
            "                        and plan.invalid_flag = '1' " +
            "                        and task.check_date <= ?1 ",nativeQuery = true)
    List<BpInvestigateTask> getClosedTask(Date currDate);
}
